<template>
  <el-select
    ref="select"
    v-model="resultLabel"
    :multiple="multiple"
    :clearable="clearable"
    :placeholder="placeholder"
    :filter-method="remoteMethod"
    filterable
    size="small"
    @clear="clearHandle"
    @change="changeValue">
    <el-option :value="resultLabel">
      <el-tree
        ref="tree"
        :data="options"
        :props="props"
        :check-strictly="checkStrictly"
        :node-key="props.value"
        :show-checkbox="multiple"
        :default-checked-keys="checkedKeys"
        :filter-node-method="filterNode"
        highlight-current
        default-expand-all
        @node-click="handleNodeClick"
        @check="handleCheckChange" />
    </el-option>
  </el-select>
</template>
<script>
export default {
  name: 'ElTreeSelect',
  props: {
    // 初始值
    value: {
      type: Array | String
    },
    // 配置项
    props: {
      type: Object,
      default: () => {
        return {
          value: 'id',
          children: 'children',
          label: 'name'
        }
      }
    },
    // 选项列表数据
    options: {
      type: Array,
      default: () => {
        return []
      }
    },
    // 可清空选项
    clearable: {
      type: Boolean,
      default: true
    },
    // 是否多选
    multiple: {
      type: Boolean,
      default: false
    },
    // 提示词
    placeholder: {
      type: String,
      default: '请选择'
    },
    checkStrictly: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      resultValue: this.multiple ? [] : '',
      resultLabel: this.multiple ? [] : '',

      // 选定的key和完整的值
      checkedKeys: [],
      checkedNodes: []
    }
  },
  watch: {
    value() {
      this.resultValue = this.value
    },
    resultValue: {
      handler(val) {
        // 回显选定的节点
        let list = []
        if (this.multiple) {
          if (val && val.length > 0) {
            val.forEach(item => list.push(item[this.props.value]))
          }
        } else {
          list = [val]
        }
        this.checkedKeys = list
        // 同步选定
        setTimeout(() => {
          this.initShow()
        }, 100)
      },
      deep: true
    },
    options() {
      this.initShow()
    }
  },
  mounted() {
    this.resultValue = this.value
  },
  methods: {

    // 回显
    initShow() {
      // 先清理
      this.checkedNodes = []
      this.checkedKeys = []
      this.resultLabel = this.multiple ? [] : ''

      // 从完整树结构中回显值
      this.options.forEach((item) => {
        this.fillChildren(item)
      })
    },

    // 填充
    fillChildren(item) {
      if (this.multiple) {
        const i = this.resultValue.find((vv) => {
          return vv === item[this.props.value]
        })
        if (i) {
          const exists = this.checkedNodes.find((node) => {
            return node[this.props.value] === item[this.props.value]
          })
          if (!exists) {
            this.checkedNodes.push(item)
            this.resultLabel.push(item[this.props.label])
          }
        }
      } else {
        if (this.resultValue === item[this.props.value]) {
          this.checkedNodes = [item]
          this.resultLabel = item[this.props.label]
          return
        }
      }

      const children = item[this.props.children]
      if (children && children.length > 0) {
        for (let i = 0; i < children.length; i++) {
          this.fillChildren(children[i])
        }
      }
    },

    // 单选节点处理
    handleNodeClick(node) {
      if (!this.multiple) {
        // 单选直接返回
        this.resultLabel = node[this.props.label]
        this.resultValue = node[this.props.value]
        this.$emit('input', this.resultValue)
        this.$refs.select.blur()
      }
    },

    // 多选节点处理
    handleCheckChange() {
      const allNodes = this.$refs.tree.getCheckedNodes(true, false)
      if (allNodes.length === 0) {
        this.$emit('input', [])
        return
      }
      const values = []
      for (let i = 0; i<allNodes.length; i++) {
        const node = allNodes[i]
        values.push(node[this.props.value])
      }
      this.resultValue = values
      this.$emit('input', this.resultValue)
    },

    // 从输入框中直接删除某个值时
    changeValue(val) {
      if (!this.multiple) {
        return
      }
      // 移除元素
      this.checkedNodes.forEach(node => {
        const i = val.indexOf(node[this.props.label])
        if (i === -1) {
          // 移除值
          this.resultValue.splice(this.resultValue.indexOf(node[this.props.value]), 1)
          this.checkedKeys.splice(this.checkedKeys.indexOf(node[this.props.value]), 1)
        }
      })
      this.$refs.tree.setCheckedKeys(this.checkedKeys)
      this.$emit('input', this.resultValue)
    },
    // 清除选中
    clearHandle() {
      this.resultLabel = this.multiple ? [] : ''
      this.resultValue = this.multiple ? [] : ''
      this.clearSelected()
      this.$emit('input', this.resultValue)
      this.$refs.tree.setCheckedKeys([])
    },
    // 清空选中样式
    clearSelected() {
      const allNode = document.querySelectorAll('#tree-option .el-tree-node')
      allNode.forEach((element) => element.classList.remove('is-current'))
    },

    remoteMethod(query) {
      this.$refs.tree.filter(query)
    },
    filterNode(value, data) {
      if (!value) return true
      return data[this.props.label].indexOf(value) !== -1
    }
  }
}
</script>
<style scoped>
.el-scrollbar .el-scrollbar__view .el-select-dropdown__item {
  height: auto;
  max-height: 400px;
  padding: 0;
  overflow-y: auto;
}
::v-deep .el-select__tags {
  flex-wrap: inherit !important;
  overflow-x: auto !important;
  scrollbar-width: none !important;
}
.el-select-dropdown__item.selected {
  font-weight: normal;
}

ul li >>> .el-tree .el-tree-node__content {
  height: auto;
  padding: 0 5px;
}
.el-tree-node__label {
  font-weight: normal;
}
.el-tree >>> .is-current .el-tree-node__label {
  color: #409EFF;
  font-weight: 700;
}
.el-tree >>> .is-current .el-tree-node__children .el-tree-node__label {
  color: #606266;
  font-weight: normal;
}
.el-popper {
  z-index: 9999;
  margin-bottom: -3px
}

</style>
